layui.define(['table','laydate','layer','form','tree','upload','util','dropdown'],function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
  var $ = layui.$,
  	table = layui.table,
	dropdown = layui.dropdown,
  	layer = layui.layer,
  	upload = layui.upload,
  	form = layui.form,
	tree = layui.tree,
  	laydate = layui.laydate;
  	var optName,selectedNode;
	loadTree();
  	var tableObj = table.render({
  	  id: 'main-table',
  	  elem: '#table', //指定原始表格元素选择器（推荐id选择器）
  	  url: '/boss/openssl/usercert-tableview-data',
  	  method:'post',
  	  autoSort : false,
  	  size: 'sm',
	  even: true,
  	  toolbar: '#toolbar',
  	  defaultToolbar:['filter'],
  	  height: 'full-70',
  	  limits : [10,30,50,100],
  	  limit: 30,
  	  page: true,
  	  cols: [[
  		  {type:'checkbox'},
  		  {field: 'commonName', title: '通用名',sort:false,width:210,templet: function(d){
  			  switch(d.commonName) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return d.commonName;
  			  }
  	      }},
  		  {field: 'cerSerial', title: '证书序号',sort:false,templet: function(d){
  			  switch(d.cerSerial) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return d.cerSerial;
  			  }
  	      }},
  		  {field: 'startTime', title: '开始时间',sort:false,width:150,templet: function(d){
			switch(d.startTime) {
				case null:
					return '空';
				case '':
					return '--';
				default:
					return d.startTime;
			}
		}},
  		  {field: 'endTime', title: '截止时间',sort:false,width:150,templet: function(d){
  			  switch(d.endTime) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return d.endTime;
  			  }
  	      }},
  		  {field: 'cerStatus', title: '证书状态',sort:false,width:100,templet: function(d){
  			  switch(d.cerStatus) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	case 'NORMAL':
  			  		return '<font color=green>使用中</font>';
  			  	case 'INVOKED':
  			  		return '<font color=red>已吊销</font>';
  			  	case 'GENFAIL':
  			  		return '生成失败';
  			  	default:
  			  		return d.cerStatus;
  			  }
  	      }},
  		  {fixed: 'right', title:'操作', toolbar: '#optbar', width:175}
  	  ]],
  	  parseData: function(res){
	  }
  	});

  	/** 顶部toolbar事件 **/
  	table.on('toolbar(table)', function(obj){
  		switch(obj.event){
  		  case 'refresh-opt':
			    tableObj.reload();
			  break;
  		  case 'addData-opt':
			  if(selectedNode == undefined){
				  layer.alert('请先选择CA证书',{icon: 5});
				  return;
			  }
			  $('#cerPid-win').val(selectedNode);
			  $('#cerType-win').val('USER');
  			  layer.open({
  				  type: 1,
  				  area: ['700px','450px'],
  				  title : '新增证书',
  				  content: $('#windows'),
  				  resize : false,
  				  move : false,
  				  shadeClose : false,
  				  btn : [ '确定', '取消' ],
  				  success : function(layero, index){
  					  $('#win-form')[0].reset();
  				  },
				  yes : function(index, layero) {
					  $('#win-submit').trigger('click');
				  }
  				});
	      break;
  		  case 'batch-del-opt':
  			  var checkStatus = table.checkStatus('main-table');
  			  if(checkStatus.data.length ==0){
  				  layer.alert('请先选择待删除行',{icon: 5});
  				  return;
  			  }
  			  layer.confirm("你确定批量删除"+checkStatus.data.length+"个项目吗？", {icon: 3, title:'提示'},
  			            function(index){//确定回调
      				  		var keys = new Array();
      				  		$.each(checkStatus.data,function(i,item){
      				  			keys.push(item.shortCutId);
      				  		});
      				  		batchDelete(keys,index);
  			            },function (index) {//取消回调
  			               layer.close(index);
  			            }
  			        );
  			  break;
  		}
  	});
	form.verify({
		countryName:function (value,item) {
			if(value.length>2){
				return "国家字段长度不能大于2";
			} else if(value.length == 0){
				return "国家字段必填";
			}
		},
		cerPasswd: function (value,item) {
			if(value.length<4){
				return "密码最小4位";
			} else if(value.length == 0){
				return "密码字段必填";
			}
		}
	});
  	form.on('submit(win-submit)', function(data){
		$.ajax({
			type: 'POST',
			url: '/boss/openssl/usercert-add',
			data: data.field,
			success: function (data) {
				if(data.success){
					layer.closeAll();
					tableObj.reload();
					loadTree();
					layer.msg(data.message);
				}else{
					layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
				}
			},
			error: function(data) {
				layer.msg(data.responseJSON.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
			},
			dataType: "json"
		});
		return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
	});
  	
  	/** 右侧tool事件 **/
  	table.on('tool(table)', function(obj){
  		var data = obj.data;
  		switch(obj.event){
  		  case 'detail-opt':
  			  optName = 'view';
  			  layer.open({
  				  type: 1,
  				  area: ['700px','670px'],
  				  title : '查看',
  				  content: $('#detail_window'),
  				  shadeClose : false,
  				  move : false,
  				  btn : [ '取消' ],
  				  success : function(layero, index){
  					  $('#win-form')[0].reset();
  					  $.post(
  							  "/boss/openssl/usercert-get",
  							  {cerId:data.cerId},
  							  function(data, textStatus, jqXHR){
  								  form.val("detail-win-form",data);
  							  },"json");
  				  },
				  btn1 : function(index, layero) {
					  layer.close(index);
				  }
  				});
  			  break;
		  case 'revoke-opt':
		  	layer.confirm("你确定吊销证书“"+obj.data.commonName+"”吗？", {icon: 3, title:'提示'},
				function(index){//确定回调
					$.ajax({
						type: 'POST',
						url: '/boss/openssl/revokecert',
						data: {caid: selectedNode, cerid:data.cerId},
						success: function (data) {
							if(data.success){
								layer.closeAll();
								tableObj.reload();
								loadTree();
								layer.msg(data.message);
							}else{
								layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
							}
						},
						error: function(data) {
							layer.msg(data.responseJSON.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
						},
						dataType: "json"
					});
				},function (index) {//取消回调
					layer.close(index);
					return;
				}
			);
			break;
  		  case 'del-opt':
			layer.confirm("你确定删除证书“"+obj.data.commonName+"”吗？", {icon: 3, title:'提示'},
				function(index){//确定回调
					deleteCer(obj.data.cerId,index);
				},function (index) {//取消回调
					layer.close(index);
				}
			);
			break;
		  case 'download-opt':
			var that = this,data = obj.data;
		    dropdown.render({
				elem: that,
				show: true,
				data: [{
					title: '私钥',
					id: 100
				},{
					title: '私钥（不带密码）',
					id: 101
				},{
					title: '公钥',
					id: 102
				},{
					title: 'PKCS12证书',
					id: 103
				},{
					title: 'Nginx证书打包下载',
					id: 104
				}],
				click: function(data, othis){
					switch (data.id) {
					case 100:
						location.href="/boss/openssl/usercert-download?cerId="+obj.data.cerId+"&downloadType=key_cer";
						break;
					case 101:
						location.href="/boss/openssl/usercert-download?cerId="+obj.data.cerId+"&downloadType=key_cer_nopasswd";
						break;
					case 102:
						location.href="/boss/openssl/usercert-download?cerId="+obj.data.cerId+"&downloadType=user_cer";
						break;
					case 103:
						location.href="/boss/openssl/usercert-download?cerId="+obj.data.cerId+"&downloadType=pkcs12";
						break;
					case 104:
						layer.open({
							type: 1,
							area: ['700px','550px'],
							title : 'Nginx配置',
							content: $('#nginx_window'),
							resize : false,
							move : false,
							shadeClose : false,
							btn : [ '下载', '取消' ],
							yes : function(index, layero) {
								location.href="/boss/openssl/nginx-config-download?cerid="+obj.data.cerId;
							}
						 });
						break;
					default:
						break;
					}
				}
			});
			break;
  		}
  	});

	function deleteCer(keys,index){
		$.ajax({
			  type: 'POST',
			  url: '/boss/openssl/usercert-delete',
			  data: {cerId:keys},
			  success: function (data) {
				  if(data.success){
					  layer.close(index);
				  }else{
					  layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
				  }
				  tableObj.reload();
				  layer.msg(data.message);
			  },
			  error: function(data) {
				  layer.msg(data.responseText,{icon: 5,anim: 6,title:'错误',time: 0,btn:['确定']});
			  },
			  dataType: "json"
		  });
	}

	dropdown.render({
		elem: '#ca-opt',
		data: [{
		  title: '根CA',
		  id: 100
		},{
		  title: '二级CA',
		  id: 101
		}],
		click: function(obj){
		  switch (obj.id) {
			case 100:
				$('#cerType-win').val('ROOTCA');
				ca_title="新增ROOTCA证书";
			  break;
			case 101:
				$('#cerType-win').val('SUBCA');
				if(selectedNode == undefined){
					layer.alert('请先选择ROOTCA',{icon: 5});
					return;
				}
				$('#cerPid-win').val(selectedNode);
				ca_title="新增二级CA证书";
				break;
			 default:
			  break;
		  }
		  layer.open({
            type: 1,
            area: ['700px','450px'],
            title : ca_title,
            content: $('#windows'),
            resize : false,
            move : false,
            shadeClose : false,
            btn : [ '确定', '取消' ],
            success : function(layero, index){
                $('#win-form')[0].reset();
            },
            yes : function(index, layero) {
                $('#win-submit').trigger('click');
            }
		   });
		}
	  });
	dropdown.render({
		elem: '#more-opt',
		data: [{
		  title: '下载CRL文件',
		  id: 100
		},{
	        title: '恢复与备份',
	        child: [{
			  title: '下载当前备份',
			  id: 101
			},{
			  title: '上传恢复',
			  id: 102
			}]
        },{type: '-'},
		{
		  title: '配置文件',
		  id: 103
		}],
		click: function(obj){
		  switch (obj.id) {
			case 100:
				if(selectedNode==undefined){
					layer.msg('请先点一下CA证书！');
					return;
				}
				location.href="/boss/openssl/crl-download?cerId="+selectedNode;
			  break;
			 case 101:
				location.href="/boss/openssl/backup/backup-all";
			  break;
			 case 102:
				$('#upload-opt').click();
			  break;
			 case 103:
			 	layer.open({
					type: 1,
					area: ['1024px','670px'],
					title : 'OpenSSL配置',
					content: $('#openssl_edit_window'),
					shadeClose : false,
					move : false,
					btn : [ '取消' ],
					success : function(layero, index){
						$('#win-form')[0].reset();
						$.post(
								"/boss/openssl/config/get",
								{cerId:selectedNode},
								function(data, textStatus, jqXHR){
									$('#config-win').val(data.message);
								},"json");
					},
					btn1 : function(index, layero) {
						layer.close(index);
					}
				});
			  break;
			 default:
			  break;
		  }
		}
	  });
	upload.render({
	    elem: '#upload-opt',
	    url: '/boss/openssl/backup/restore-backup-all',
	    auto: true,
	    accept: 'file',
	    exts:	'zip',
	    done: function(res, index, upload){
	      layer.msg(res.message);
	    }
	});
	$('#viewca-opt').click(function () {
		if(selectedNode==undefined){
			layer.msg('请选择证书！');
			return;
		}
		layer.open({
			type: 1,
			area: ['700px','670px'],
			title : '查看',
			content: $('#detail_window'),
			shadeClose : false,
			move : false,
			btn : [ '取消' ],
			success : function(layero, index){
				$('#win-form')[0].reset();
				$.post(
						"/boss/openssl/usercert-get",
						{cerId:selectedNode},
						function(data, textStatus, jqXHR){
							form.val("detail-win-form",data);
						},"json");
			},
			btn1 : function(index, layero) {
				layer.close(index);
			}
		});
	});

	function loadTree(){
	$.post(
		'/boss/openssl/tree-data-source',
		null,
		function(data, textStatus, jqXHR){
			treeObject = tree.render({
				id: 'cer_tree',
				elem: '#cer_tree',
				data : data,
				// 显示多选框
				showCheckbox : false,
				accordion : false,
				onlyIconControl : true,
				edit : ['del'],
				click : function(obj){
                    // console.log(obj.data);
					selectedNode = obj.data.id;
					tableObj.reload({where:{
						cerPid:obj.data.id
					}});
				},
				operate: function(obj){
					var type = obj.type; //得到操作类型：add、edit、del
					var data = obj.data; //得到当前节点的数据
					var elem = obj.elem; //得到当前节点元素
					var id = data.id; //得到节点索引
					if(type === 'del'){ //删除节点
                        var keys = new Array();
                        keys.push(data.id);
                    };
				}
			});
		},"json");
	}
  
  //输出opensslPage接口
  exports('opensslPage', {});
});